package edu.hunau.cxb19.oop.class32.tcp.v5;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

/**
 *
 * @author hb
 *
 *         2020-04-21 16:23:09
 */
public class ServerTcp {
	private ServerSocket serverSocket;

	public ServerTcp() {
		try {
			serverSocket = new ServerSocket(8088);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void start() {
		try {
			System.out.println("等待客户端的连接....");
			while (true) {
				Socket socket = serverSocket.accept();
				ClientHandler clientHandler = new ClientHandler(socket);
				// 将获得的Socket实例由线程进行维护
				new Thread(clientHandler).start();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	/**
	 * 提供一个内部类,创建线程维护一个Socket实例
	 * 
	 * @param args
	 */
	private class ClientHandler implements Runnable {
		private Socket socket;

		public ClientHandler(Socket socket) {
			this.socket = socket;
		}

		@Override
		public void run() {
			try {
				System.out.println("客户端已经连接!");
				// 读取客户端的消息
				InputStream is = socket.getInputStream();
				InputStreamReader isr = new InputStreamReader(is, "utf-8");
				BufferedReader br = new BufferedReader(isr);
				while (true) {
					String data = br.readLine();
					System.out.println(data);
					if (data.endsWith("exit")) {
						System.out.println("客户端下线");
						break;
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) {
		ServerTcp server = new ServerTcp();
		server.start();
	}
}
